﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using Quickie.Models;
using Quickie.Models.IoC;
using Quickie.Models.Data;
using Quickie.Models.Entities;
using Quickie.Models.ViewModel;
using Quickie.Models.Interfaces;

namespace Quickie.Models.Data
{
    public class PersonRepository : IRepository<Person>
    {
        private readonly IDataProvider data;

        public PersonRepository(IDataProvider data)
        {
            this.data = data;
        }

        public IQueryable<Person> GetAll()
        {
            return data.Linq<Person>();
        }

        public Person GetByID(int ID)
        {
            try
            {
                return GetAll().Single(x => x.ID == ID);
            }
            catch (Exception)
            {
                return null;
            }
        }

        public void Save(Person item)
        {
            data.Insert(item);
            data.SubmitChanges();
        }

        public void Delete(Person item)
        {
            data.Delete(item);
        }

        public void SaveChanges()
        {
            data.SubmitChanges();
        }
    }

    public static class PersonRepExtensions
    {
        public static List<Person> FromCompany(this IRepository<Person> source, int ID)
        {
            var context = new DataClassesDataContext();
            var options = new DataLoadOptions();
            options.LoadWith<Person>(p => p.Company);
            context.LoadOptions = options;

            var persons = from c in context.Companies
                        join p in context.Persons on c.ID equals p.CompanyID
                        where c.ID == ID 
                        select p;

            return persons.ToList();
        }
    }

}
